﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Win32;
using System.Web.UI;
using System.Web;

namespace Macaw.Moss2007.SearchEnhancements
{
    public class NoIndex : Control
    {
        public NoIndex()
        {
            OnlyMossSearch = true;
        }

        public bool OnlyMossSearch { get; set; }

        private static string MossCrawlerUserAgent = null;

        protected bool IsMossCrawler(HttpRequest request)
        {
            if (MossCrawlerUserAgent == null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Office Server\\12.0\\Search\\Global\\Gathering Manager");
                    if (key != null)
                    {
                        MossCrawlerUserAgent = (string)key.GetValue("UserAgent");
                    }
                });
            }

            if (!string.IsNullOrEmpty(MossCrawlerUserAgent))
            {
                if (string.Equals(request.UserAgent, MossCrawlerUserAgent, StringComparison.InvariantCultureIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }


        protected override void Render(HtmlTextWriter writer)
        {
            if (HttpContext.Current != null)
            {
                if (
                    (!OnlyMossSearch && HttpContext.Current.Request.Browser.Crawler) ||
                     (OnlyMossSearch && IsMossCrawler(HttpContext.Current.Request))
                    )
                {
                    return;
                }
            }
            base.Render(writer);
        }

    }
}
